<?php
/**
 * 平台菜单
 * User: cxm
 * Date: 2019/10/21
 * Time: 10:25
 */
namespace App\Http\Controllers\Admin\Menu;
use App\Http\Controllers\Admin\Controller;
use App\Models\AdminPermission;
use DB,Validator;
use Illuminate\Http\Request;

class AdminMenuController extends Controller {

    /**
     * 添加、编辑修改
     * URL POST:/admin/menu/store
     * @param Request $request
     * @param int id 菜单ID 编辑时传
     * @param int pid 父级ID 0为顶级菜单
     * @param string name 菜单名称
     * @param int fid 附属权限ID 例如 添加 添加提交操作为附属权限 添加的ID的附属权限ID
     * @param string icon 图标
     * @param int menu_switch 是否显示菜单 1不显示2显示
     * @param int sort 排序
     * @param array http_method 访问方式 POST GET
     * @param string http_path 地址
     * @param string slug 标识  菜单显示效果 可以为空
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function store(Request $request){
        $params = $request->only(['id','pid','name','fid','icon','menu_switch','sort','http_method','http_path','url','slug']);
        $id = isset($params['id']) ? $params['id'] : 0;
        $validator = Validator::make($params,[
            'name'          => ['required'],
            'menu_switch'   => ['required'],
            //'http_method'   => ['required'],
            //'http_path'     => ['required']
        ],[
            'name.required'             => '菜单名称不能为空',
            'menu_switch.required'      => '请选择是否显示菜单',
            //'http_method.required'      => '请求方式不能为空',
            //'http_path.required'        => '地址不能为空'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if ($id==0) {
            $menu = new AdminPermission();
        }else{
            $menu = AdminPermission::find($id);
            if (!$menu) {
                return $this->error('菜单不存在');
            }
        }
        DB::beginTransaction();
        try{
            $menu->pid              = isset($params['pid']) ? $params['pid'] : 0;
            $menu->name             = $params['name'];
            $menu->fid              = isset($params['fid']) ? $params['fid'] : 0;
            $menu->icon             = isset($params['icon']) ? $params['icon'] : '';
            $menu->menu_switch      = $params['menu_switch'];
            $menu->sort             = isset($params['sort']) ? $params['sort'] : 1;
            $menu->http_method      = isset($params['http_method']) ? implode(',',$params['http_method']) : 'javascript:;';
            $menu->url              = isset($params['url']) ? $params['url'] : '';// 路由
            $menu->http_path        = isset($params['http_path']) ?$params['http_path'] : '';// 地址
            $menu->slug             = isset($params['slug']) ? $params['slug'] : '';
            if($menu->save()){
                $this->refreshPermission($menu->id);
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**
     * 修改文字分类的pid和level字段
     * @param $id
     */
    public function refreshPermission($id)
    {
        $subject       = new AdminPermission(); // 实例化User对象
        $cate         = $subject->where("id", $id)->first()->toArray(); // 找出他自己
        $table_prefix = DB::getTablePrefix();// 表前缀
        // 刚新增的分类先把它的值重置一下
        if ($cate['path'] == '') {
            ($cate['pid'] == 0) && DB::update("UPDATE {$table_prefix}admin_permission set  path = '0,$id', level = 1 where id = $id"); // 如果是一级分类
            DB::update("UPDATE {$table_prefix}admin_permission AS a ,{$table_prefix}admin_permission AS b SET a.path = CONCAT_WS(',',b.path,'$id'),a.level = (b.level+1) WHERE a.pid=b.id AND a.id = $id");
            $cate = $subject->where("id", $id)->first()->toArray(); // 从新找出他自己
        }

        if ($cate['pid'] == 0) { //有可能是顶级分类 他没有老爸
            $parent_cat['path']  = '0';
            $parent_cat['level'] = 0;
        } else {
            $parent_cat = $subject->where("id", $cate['pid'])->first()->toArray(); // 找出他老爸的parent_id_path
        }
        $replace_level = $cate['level'] - ($parent_cat['level'] + 1); // 看看他 相比原来的等级 升级了多少  ($parent_cat['level'] + 1) 他老爸等级加一 就是他现在要改的等级
        $replace_str   = $parent_cat['path'] . ',' . $id;
        DB::update("UPDATE `{$table_prefix}admin_permission` SET path = REPLACE(path,'{$cate['path']}','$replace_str'), level = (level - $replace_level) WHERE  path LIKE '{$cate['path']}%'");
    }

    /**
     * 获取菜单列表
     * URL GET:/admin/menu/get-lists
     * @param string keyword 关键字
     * @param int is_page 是否分页 1是2否
     * @param int pid 父ID
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return \Illuminate\Http\JsonResponse {code:错误码，msg:错误信息，data:返回参数}
     */
    public function getLists(Request $request){
        $params = $request->only(['keyword','pid','is_page','page','limit']);
        $is_page = isset($params['is_page']) ? $params['is_page'] : 2;
        $where = [];
        if (!empty($params['keyword'])) {
            $where[] = ['name','like','%'.$params['keyword'].'%'];
        }
        if ($is_page == 1) {
            $page = isset($params['page']) ? $params['page'] : 1;
            $pid = isset($params['pid']) ? $params['pid'] : 0;
            $where[] = ['pid',$pid];
            $limit = isset($params['limit']) ? $params['limit'] : config('exam.pageSize');
            $data = AdminPermission::getData($where,[],$page,$limit);
            // 查询上级ID
            $parent_id = AdminPermission::findFatherId($pid);
            $data['parent_id'] = !isset($parent_id) ?  -1 : $parent_id ;
        }else{
            $first = [
                "value" => 0,
                "label" => "顶级菜单",
                "children" => []
            ];
            $data = AdminPermission::dataGroup();
            array_unshift($data,$first);
        }
        return $this->success('操作成功',$data);
    }

    /**
     * 删除
     * URL POST:/admin/menu/delete
     * @param Request $request
     * @param array ids 菜单ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request){
        $params = $request->only(['ids']);
        if (empty($params['ids'])) {
            return $this->error('缺少菜单ID');
        }
        // 查看父级是否存在
        if (AdminPermission::isFather($params['ids'])) {
            return $this->error('存在下级，请先删除下级菜单');
        }
        $result  = AdminPermission::whereIn('id',$params['ids'])->delete();
        if (!$result) {
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }

    /**
     * 是否隐藏
     * URL POST:/admin/menu/isShow
     * @param Request $request
     * @param int id 菜单ID
     * @return mixed
     */
    public function isShow(Request $request){
        $params = $request->only(['id']);
        if (!array_key_exists('id',$params) || $params['id'] < 1) {
            return $this->error('缺少菜单ID');
        }
        $menu = AdminPermission::find($params['id']);
        if (!$menu) {
            return $this->error('菜单不存在');
        }
        $status = $menu->menu_switch == 1 ? 2 : 1;
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['menu_switch'=>$status];
        $result = AdminPermission::modify($where,$field);
        if (!$result) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 修改排序
     * URL POST:/admin/menu/editSort
     * @param Request $request
     * @param int id 菜单ID
     * @param int sort  排序
     * @return mixed
     */
    public function editSort(Request $request){
        $params = $request->only(['id','sort']);
        if (!array_key_exists('id',$params) || $params['id'] < 1) {
            return $this->error('缺少菜单ID');
        }

        if (!array_key_exists('sort',$params) || $params['sort'] < 1) {
            return $this->error('请输入排序值');
        }

        $menu = AdminPermission::find($params['id']);
        if (!$menu) {
            return $this->error('菜单不存在');
        }
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['sort'=>$params['sort']];
        $data = AdminPermission::modify($where,$field);
        if (!$data){
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    /**
     * 保存信息到文件
     * URL POST:/admin/menu/saveFile
     * @param Request $request
     * @return mixed
     */
    public function saveFile(Request $request){
        set_time_limit(0);
        AdminPermission::dataSaveFile();
        return $this->success('成功');
    }

    /**
     * 详情
     * URL POST:/admin/menu/edit
     * @param Request $request
     * @param int id 详情ID
     * @return mixed
     */
    public function edit(Request $request){
        $params = $request->only(['id']);
        if (!isset($params['id']) || empty($params['id'])) {
            return $this->error('缺少菜单ID');
        }
        $menu = AdminPermission::find($params['id']);
        $parent_id = explode(',',$menu->path);
        array_shift($parent_id);
        foreach ($parent_id as &$item) {
            $item = (int) $item;
        }
        $menu->parent_id = $parent_id;
        return $this->success('查询成功',$menu);
    }
}